package com.hutao.manage.controller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import javax.imageio.ImageIO;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hutao.manage.component.Config;
import com.hutao.manage.util.ExceptionUtil;
import com.hutao.manage.util.FileUtil;
import com.hutao.manage.util.GraphicsMagicUtil;
import com.hutao.manage.util.Result;
import com.hutao.manage.util.RoateImage;

@Controller
@RequestMapping("/image")
public class ImageController {
	private static final Logger log = LoggerFactory.getLogger(ImageController.class);

	@Autowired
	private Config config;
	
	@ResponseBody
	@RequestMapping("/imageRotate")
	public Result imageRoate(String imagePath ,int angle) {
		Result result = null;
		InputStream inputStream = null;
		try {
			String suffixName = FileUtil.getSuffixName(imagePath);
			if (StringUtils.isBlank(suffixName)) {
				log.error("图片旋转操作文件没有没有后缀名" + imagePath);
				return new Result(false, "文件没有没有后缀名" + imagePath, null, 500);
			}
			
			String imgPath=config.getUploadResourcePath()+imagePath;
			inputStream = new FileInputStream(new File(imgPath));
			BufferedImage src = ImageIO.read(inputStream);
			//顺时针旋转90度
	        BufferedImage des1 = RoateImage.Rotate(src, angle);
	        ImageIO.write(des1, "jpg", new File(imgPath));
			result = new Result(true, "成功", null, 200);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("-----imageRotate异常------" + ExceptionUtil.getStackTrace(e));
			result = new Result(false, "系统异常:" + ExceptionUtil.getStackTrace(e), null, 500);
		} finally {
			IOUtils.closeQuietly(inputStream);
			
		}
		return result;
	}
	
	@ResponseBody
	@RequestMapping("/imageRotate1")
	public Result imageRoate1(String imagePath ,int angle) {
		Result result = null;
		try {
			String imgPath=config.getUploadResourcePath()+imagePath;
			GraphicsMagicUtil.rotate(imgPath, imgPath, angle);
			result = new Result(true);
		} catch (Exception e) {
			
			e.printStackTrace();
			result = new Result(false);
		}
		return result;
	}
}
